"""
种子生成器 - 调用AI API生成种子
"""

import dashscope
import time
from config.prompts import build_prompt


class SeedGenerator:
    def __init__(self, api_key):
        dashscope.api_key = api_key
        self.retry_count = 3
        self.retry_delay = 2

    def generate_seeds(self, program_path, analysis, program_info):
        """生成种子文件"""

        # 构建提示词
        prompt, expected_seed_count = build_prompt(
            program_info, analysis, analysis['program_type']
        )

        messages = [{'role': 'user', 'content': prompt}]

        # 带重试机制的API调用
        for attempt in range(self.retry_count):
            try:
                print(f" 调用AI生成种子 (尝试 {attempt + 1}/{self.retry_count})...")

                response = dashscope.Generation.call(
                    dashscope.Generation.Models.qwen_turbo,
                    messages=messages,
                    result_format='message',
                    timeout=60  # 60秒超时
                )

                if response.status_code == 200:
                    seeds_text = response.output.choices[0].message.content
                    return seeds_text, expected_seed_count
                else:
                    print(f"❌ API调用失败: {response.code} - {response.message}")
                    if attempt < self.retry_count - 1:
                        time.sleep(self.retry_delay)

            except Exception as e:
                print(f"❌ 发生错误: {e}")
                if attempt < self.retry_count - 1:
                    time.sleep(self.retry_delay)

        return None, 0